package com.lin.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码
 *      后端需要使用
 */
public class ImageServlet extends HelloServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置浏览器10秒刷新
        resp.setHeader("refresh", "60");

        // 生成验证码
        String verifyCode = createVerifyCode();

        // 创建字体
        Font font = new Font("微软雅黑", Font.BOLD, 20);

        // 创建一个临时的 BufferedImage 来获取 Graphics2D 对象
        BufferedImage tempImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D tempGraphics = tempImage.createGraphics();
        tempGraphics.setFont(font);

        // 获取 FontMetrics
        FontMetrics fontMetrics = tempGraphics.getFontMetrics();

        // 计算验证码字符串的宽度和高度
        Rectangle2D bounds = fontMetrics.getStringBounds(verifyCode, tempGraphics);
        int codeWidth = (int) bounds.getWidth();
        int codeHeight = (int) bounds.getHeight();

        // 设置图片宽度和高度
        int imageWidth = codeWidth + 20; // 添加一些边距
        int imageHeight = 30;

        // 内存中创建图片
        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        // 获取画笔
        Graphics2D graphics = image.createGraphics();
        // 设置抗锯齿
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 设置画笔颜色
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, imageWidth, imageHeight);
        graphics.setColor(Color.BLUE);
        graphics.setFont(font);
        // 计算字符串的起始位置以使其居中
        int x = (imageWidth - codeWidth) / 2;
        int y = (imageHeight - codeHeight) / 2 + fontMetrics.getAscent();
        graphics.drawString(verifyCode, x, y);

        // 释放临时 Graphics2D 对象
        tempGraphics.dispose();

        // 设置浏览器响应头
        resp.setContentType("image/jpeg");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);
        // 输出图片
        ImageIO.write(image, "jpg", resp.getOutputStream());

        // 释放 Graphics2D 对象
        graphics.dispose();
    }


    private String createVerifyCode() {
        String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int len = base.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            int index = (int) (Math.random() * len);
            sb.append(base.charAt(index));
        }
        return sb.toString();
    }

    private FontMetrics getFontMetrics(Font font) {
        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = img.createGraphics();
        FontMetrics fm = g2d.getFontMetrics(font);
        g2d.dispose();
        return fm;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
